<!DOCTYPE html>
<html lang="zh-cn">
	<head>
		<meta charset="UTF-8">
		<title class="title">水印相机</title>
		<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
	</head>

	<body>
		<div id="app"></div>
		
		<script type="text/javascript" src="js/vue.min.js"></script>
		<script src="js/uni.webview.min.1.5.5.js"></script>
		<script type="text/javascript">
			let self;
			var vm = new Vue({
				el: '#app',
				data: {
					
				},
				mounted() {
					console.log("webview加载成功");
					self = this;
					
					window.setImage = async(e) => {
						self.draw(e)
					}
				},
				methods: {
					async draw(e) {
						const img = await this.getImg(e.base64)
						let width = e.width
						let height = e.height
						const maxWidth = e.maxWidth || 750
						if(width > maxWidth) {
							height = parseInt((maxWidth / width) * height);
							width = parseInt(maxWidth);
						}
						let xRatio = Number((width / e.liveWidth).toFixed(2))
						let yRatio = Number((height / e.liveHeight).toFixed(2))
						this.canvas = document.createElement('canvas');
						this.canvas.width = width;
						this.canvas.height = height;
						this.ctx = this.canvas.getContext('2d');
						
						this.ctx.drawImage(img, 0, 0, width, height);
						await this.drawWatermark(e.watermark, xRatio, yRatio)
						
						const base64 = this.canvas.toDataURL('image/png', 0.75);
						uni.postMessage({
							data: {
								base64: base64
							}
						});
					},
					
					async drawWatermark(watermark, xRatio, yRatio) {
						for(let i=0; i<watermark.length; i++) {
							const item = watermark[i]
							switch (item.type){
								case 'text':
									this.ctx.font = item.isBold ? "bold "+ item.size * yRatio +"px Arial" : "normal "+item.size * yRatio+"px Arial";
									this.ctx.fillStyle = item.color;
									this.ctx.fillText(item.text, item.x * xRatio, (item.y + item.size) * yRatio);
									break;
								case 'fillRect':
									this.ctx.fillStyle = item.color
									this.ctx.fillRect(item.x * xRatio, item.y * yRatio, item.w * yRatio, item.h * yRatio);
									break;
								case 'image':
									const img = await this.getImg(item.url)
									this.ctx.drawImage(img, item.x * xRatio, item.y * yRatio, item.w * yRatio, item.h * yRatio);
									break;
							}
						}
					},
					
					getImg(path) {
						return new Promise((resolve, reject) => {
							const img = new Image()
							img.crossOrigin = "Anonymous"
							img.src = path
							img.onload = function() {
								resolve(img)
							}
						})
					}
				}
			});
		</script>
	</body>
</html>
